from django.template import Context, loader
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.db import connection, transaction
from kmonitor.metric.db_wrapper import DBWrapper, getWrapperWithCursor


QUERY_KEYS = ['name', 'host',\
              'start_year','start_month','start_day',\
              'start_hour','start_min','start_sec',\
              'end_year','end_month','end_day',\
              'end_hour','end_min','end_sec']

DATA_TABLE = 'test'

def timeOpt(st, ed, formats):
  l = []
  for t in range(st, ed):
    if (formats == 2):
      l.append('%02d'%(t))
    elif (formats == 4):
      l.append('%d'%(t))
  return l

def timeOptBuilder():
  YEAR_OPT = timeOpt(2010, 2012, 4)
  MONTH_OPT = timeOpt(1, 13, 2)
  DAY_OPT = timeOpt(1, 32, 2)
  HOUR_OPT = timeOpt(1, 25, 2)
  MINUTE_OPT = timeOpt(0, 60, 2)
  return [YEAR_OPT, MONTH_OPT, DAY_OPT, HOUR_OPT, MINUTE_OPT, MINUTE_OPT]

def getValue(dicts, name):
  val = None
  try:
    val = dicts[name]
  except KeyError, e:
    pass
  return val

def checkParam(key, val):
  return None

def errorMessage(msg):
  t = loader.get_template('error.html')
  c = Context({'errorMsg': msg})
  return render_to_string('error.html', c)

def getOptions(keys, db, table):
  options = {}
  for key in keys:
    options[key] = db.selectDistinct(table, key)
  return options

def index(request):
  if request.path != '/':
    return HttpResponse('');

  vals = {}
  for key in QUERY_KEYS:
    vals[key] = getValue(request.GET, key)
    msg = checkParam(key, vals[key])
    if (msg is not None):
      return HttpResponse(errorMessage(msg))

  db = getWrapperWithCursor(connection.cursor())

  options = {}
  jsonData = []
  priceData = []
  summaryData = []

  options['name'] = db.selectDistinct(DATA_TABLE, 'name')
  options['host'] = db.selectDistinct(DATA_TABLE, 'host')

  if (vals['name'] is not None):
    start_time = '\'%s-%s-%s %s:%s:%s\'' % \
        (vals['start_year'], vals['start_month'], vals['start_day'],\
         vals['start_hour'], vals['start_min'], vals['start_sec'])
    end_time = '\'%s-%s-%s %s:%s:%s\'' % \
        (vals['end_year'], vals['end_month'], vals['end_day'],\
         vals['end_hour'], vals['end_min'], vals['end_sec'])
    res = db.selectSeqCond(DATA_TABLE, 'time', 'value',\
          start_time, end_time, \
          'name=\'%s\' and host=\'%s\''%(vals['name'], vals['host']))
    for i in range(0, len(res)):
      jsonData.append(res[i][0].isoformat(' '))
      priceData.append([i, res[i][1]])
      if i % 5 == 0:
        summaryData.append([i, res[i][1]])
    if len(res) > 0:
      if ((len(res) - 1) % 5 != 0):
        summaryData.append([(len(res) - 1), res[len(res)-1][1]])


  timeList = timeOptBuilder()
  t = loader.get_template('base.html')
  c = Context({'nameOpt': options['name'],\
               'hostOpt': options['host'],\
               'yearOpt': timeList[0], \
               'monthOpt': timeList[1], \
               'dayOpt' : timeList[2], \
               'hourOpt' : timeList[3], \
               'minOpt' : timeList[4], \
               'secOpt' : timeList[5], \
               'jsonData': str(jsonData),\
               'priceData': str(priceData),\
               'summaryData': str(summaryData)})
  return HttpResponse(t.render(c))

def query(request, path):
  t = loader.get_template(path)
  c = Context({})
  return HttpResponse(t.render(c))
